//
//  AppDelegate.swift
//  YueChat
//
//  Created by IMac on 2024/9/10.
//

import UIKit
import UserNotifications

@main
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate {

    var window: UIWindow?
    var badgeCount = 0
    var bgTask : UIBackgroundTaskIdentifier?
    var startedInBackground = false
    var g_LastKeepAliveDate :Date?
    var g_lock = NSLock()
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        
        self.window = UIWindow(frame: UIScreen.main.bounds)
        self.window!.backgroundColor = .white
        
        self.window!.makeKeyAndVisible()
        
//        IQKeyboardManager.shared.enable = true
//        IQKeyboardManager.shared.resignOnTouchOutside = true // 当点击键盘外部时，键盘是否应该关闭
//        IQKeyboardManager.shared.toolbarConfiguration.placeholderConfiguration.showPlaceholder = false // 是否显示工具栏占位符
//        IQKeyboardManager.shared.keyboardDistance = 10 // 输入框距离键盘的距离
        
        UNUserNotificationCenter.current().delegate = self
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge]) { granted, error in
            if granted{
                DispatchQueue.main.async {
                    application.registerForRemoteNotifications()
                }
            }
        }
        
//        let userDefaults = UserDefaults.standard
//        var hostIp: String?
//
//        if userDefaults.string(forKey: "mhhy_hostip") == nil {
//            hostIp = ""
//            userDefaults.set(hostIp, forKey: "mhhy_hostip")
//        } else {
//            hostIp = userDefaults.string(forKey: "mhhy_hostip")
//        }

//        let networkService = gnetService
//        networkService?.setServerAddress(hostIp)
//        networkService.initService(hostIp: hostIp!)
//        networkService!.connect(nil, token: nil, password: nil)

//        if let savedToken = userDefaults.string(forKey: "mhhy_token"),
//           let savedUserId = userDefaults.string(forKey: "mhhy_id"),
//           !savedToken.isEmpty,
//           !savedUserId.isEmpty {
        if gosnLogin.isLogined(){
          
//            Task {
//                let (json,error) = await gosnLogin.loginWithPassword(savedUserId, savedToken)
//                if error != nil {
//                    
//                }
//            }
//            networkService?.userId = savedUserId
//            networkService?.passwd = savedToken
//            networkService?.connect(savedUserId, token: savedToken, password: nil)
//            let navController = MHHYNavigationVC(rootViewController: MHHYLoginManager.getMMDrawerController())
            InfoManager.shared.tabbar = TabBar()
            window!.rootViewController = InfoManager.shared.tabbar
        } else {
            gosnLogin.setBaseUrl("https://abc.tjlm.top:19314")
//            gosnLogin.setBaseUrl("http://121.62.23.73:19314")
//            if !UserDefaults.standard.bool(forKey: "isFirstLaunch") {
//                window?.rootViewController = GuideVC()
//                UserDefaults.standard.setValue(true, forKey: "isFirstLaunch")
//            }else{
                let navController = YLNavigationVC(rootViewController: LoginVC())
                window!.rootViewController = navController
//            }

        }

        window!.makeKeyAndVisible()

//        if #available(iOS 13.0, *) {
//            UIApplication.shared.statusBarStyle = .default
//            if let themeStr = userDefaults.string(forKey: "theme") {
//                switch themeStr {
//                case "light":
//                    window!.overrideUserInterfaceStyle = .light
//                case "dark":
//                    window!.overrideUserInterfaceStyle = .dark
//                default:
//                    window!.overrideUserInterfaceStyle = .unspecified
//                }
//            }
//        }

        
        /*
         创建tabBarController
         */
       
        
        /**
         *  设为根控制器
         */
//        window?.rootViewController = tabBarController
        
        return true
    }

    
    func setRootWindow () {
        
        if gosnLogin.isLogined(){
            self.window?.rootViewController = InfoManager.shared.tabbar
        }else {
            let navController = YLNavigationVC(rootViewController: LoginVC())
            window!.rootViewController = navController
        }
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let tokenParts = deviceToken.map { data -> String in
            return String(format: "%02.2hhx", data)
        }
        let token = tokenParts.joined()
        print("Device Token: \(token)")
        UserDefaults.standard.setValue(token, forKey: "deviceToken")
    }
    //锁屏和从后台进入前台会调用该方法
    func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
        print(notification)
    }
    func applicationProtectedDataDidBecomeAvailable(_ application: UIApplication) {
        
    }
    func applicationWillResignActive(_ application: UIApplication) { //即将推到后台
        UserDefaults.standard.setValue(true, forKey: "kIsBackground")
        startedInBackground=true;
        backgroundHandler()
    }
    
    func applicationDidEnterBackground(_ application: UIApplication) {
        
    }
    func applicationDidBecomeActive(_ application: UIApplication) {
        updateBadgeNumber(count: 0)
        if (startedInBackground) {
            startedInBackground = false;
        }
        UserDefaults.standard.setValue(false, forKey: "kIsBackground")
    }
    
    func backgroundHandler() {
            let app = UIApplication.shared
            bgTask = app.beginBackgroundTask(withName: "BackgroundTask") { [weak self] in
                app.endBackgroundTask(self?.bgTask ?? .invalid)
                self?.bgTask = .invalid
            }
        var count = 0
        DispatchQueue.global(qos: .default).async { [self] in
                while 0 < 200000 && startedInBackground{
                    Thread.sleep(forTimeInterval: 1)
                    count += 1
                    print(count)
                    if let lastKeepAliveDate = self.g_LastKeepAliveDate {
                        let currentDate = Date()
                        if currentDate.timeIntervalSince(lastKeepAliveDate) > 700 {
                            self.g_lock.lock()
                            self.g_LastKeepAliveDate = currentDate
                            self.g_lock.unlock()
                        }
                    }
                }
            }
        }
    
    //在前台调用下面该方法,该方法需要设置Background Modes --> Remote Notifications
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
            let status = application.applicationState
            switch status {
            case .active:
//                print("在前台收到推送")
                break
            case .inactive:
//                print("后台->前台")
                break
            case .background:
//                print("后台")
                break
            default:
                break
            }
            completionHandler(.newData)
    }
    
    func updateBadgeNumber(count:Int){
        UIApplication.shared.applicationIconBadgeNumber = count
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
//        updateBadgeNumber(count: 1)
        completionHandler([.alert,.sound,.badge])
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let request = response.notification.request
        let content = request.content
        let userInfo = content.userInfo
      
        if request.trigger is UNPushNotificationTrigger {
//            print("点击了远程通知")
        } else {
//            print("点击了本地通知")
        }
      
        // 完成处理，调用completionHandler
        completionHandler()
    }

}

